package org.melanesia.sql;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.sql.Types;

import org.melanesia.beans.Mapper;
import org.melanesia.converters.JavaToJdbcConverter;
import org.melanesia.exceptions.UnsupportedClassException;



public abstract class AbstractSQL {

    protected Mapper mapper;
    
    AbstractSQL(Mapper mapper) {
        this.mapper = mapper;
    }
    
    protected final void setInputParameter(CallableStatement stmt, InputParameter parameter) throws SQLException {
        String parameterName = parameter.getName();
        Object parameterValue = parameter.getValue();
        
        int jdbcType = Types.NULL;
        
        if (parameterValue != null) {
        
	        Class<?> parameterClass = parameterValue.getClass();
	        
	        JavaToJdbcConverter converter = parameter.getConverter();
	        if (converter == null) {
	        	converter = mapper.findJavaToJdbcConverter(parameterClass);
	        }
	        
	        if (converter == null) {
	        	// There is no converter, so no way to determine JDBC Type
                throw new UnsupportedClassException(parameterClass);
	        }
        
	        parameterValue = converter.convert(parameterValue, stmt, parameterName);
	        jdbcType = converter.getJdbcType();
        }
        
        // Finally, set the parameter value
        stmt.setObject(parameterName, parameterValue, jdbcType);
    }
}